<template>
  <div class="app-container">
    <el-tabs tab-position="left">
      <el-tab-pane :label="$t('profile.accountInfo')">
        <div class="w-full">
          <el-card>
            <div class="mt-5">
              <div v-if="userAvatar.avatar">
                <el-image class="w30" :src="userProfile.avatar" />
                <el-icon @click="openUploadDialog"><Edit /></el-icon>
              </div>
              <div v-else>
                <el-image class="w30" :src="avatar" />
                <el-icon @click="openUploadDialog"><Edit /></el-icon>
              </div>
            </div>
            <el-descriptions :column="1" class="mt-10">
              <el-descriptions-item>
                <template #label>
                  <el-icon class="align-middle"><User /></el-icon>
                  {{ $t("profile.username") }}
                </template>
                {{ userProfile.userFullName }}
                <el-icon @click="openEditDialog('userFullName')"><Edit /></el-icon>
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <el-icon class="align-middle"><Phone /></el-icon>
                  {{ $t("profile.phone") }}
                </template>
                {{ userProfile.userPhone }}
                <el-icon @click="openEditDialog('userPhone')"><Edit /></el-icon>
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <el-icon class="align-middle"><Message /></el-icon>
                  {{ $t("profile.email") }}
                </template>
                {{ userProfile.userEmail }}
                <el-icon @click="openEditDialog('userEmail')"><Edit /></el-icon>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </div>
      </el-tab-pane>

      <el-tab-pane :label="$t('profile.secure')">
        <el-card>
          <el-row>
            <el-col :span="16">
              <div class="font-bold">{{ $t("profile.passwd") }}</div>
              <div class="text-14px mt-2">
                {{ $t("profile.passwdTip") }}
                <el-button
                  type="primary"
                  plain
                  size="small"
                  class="ml-5"
                  @click="() => handleOpenDialog(DialogType.PASSWORD)"
                >
                  {{ $t("profile.changePasswd") }}
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <el-dialog v-model="dialog.visible" :title="dialog.title" :width="500">
      <el-form
        v-if="dialog.type === DialogType.PASSWORD"
        ref="passwordChangeFormRef"
        :model="passwordChangeForm"
        :rules="passwordChangeRules"
      >
        <el-form-item :label="$t('profile.oldPasswd')" prop="oldPassword">
          <el-input v-model="passwordChangeForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item :label="$t('profile.newPasswd')" prop="newPassword">
          <el-input v-model="passwordChangeForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item :label="$t('profile.confirmPasswd')" prop="confirmPassword">
          <el-input v-model="passwordChangeForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible = false">{{ $t("common.cancel") }}</el-button>
          <el-button type="primary" @click="handleSubmit">{{ $t("common.confirm") }}</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="avatarDialog.visible" :title="$t('user.uploadAvatar')">
      <el-upload ref="upload" :on-change="handleFileChange" :limit="1" :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">
          {{ $t("user.chooseImage") }}
        </el-button>
        <div slot="tip" class="el-upload__tip">
          {{ $t("user.avatarTip") }}
        </div>
      </el-upload>
    </el-dialog>
    <el-dialog v-model="dialogEdit.visible" @close="closeEditDialog">
      <el-form>
        <el-form-item v-if="username" :label="$t('profile.username')">
          <el-input v-model="formEdit.userFullName" />
        </el-form-item>
        <el-form-item v-if="userphone" :label="$t('profile.phone')">
          <el-input v-model="formEdit.userPhone" />
        </el-form-item>
        <el-form-item v-if="useremal" :label="$t('profile.email')">
          <el-input v-model="formEdit.userEmail" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeEditDialog">{{ $t("common.cancel") }}</el-button>
          <el-button type="primary" @click="handleEditSubmit">{{ $t("common.confirm") }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import UserAPI, { UserProfileVO, PasswordChangeForm, UserProfileForm } from "@/api/system/user";
import { useI18n } from "vue-i18n";
import avatar from "@/assets/avatar.svg";
import { UploadInstance } from "element-plus";
import { ref } from "vue";
const { t } = useI18n();
const username = ref(false);
const userphone = ref(false);
const useremal = ref(false);

const upload = ref<UploadInstance>();
const userProfile = ref<UserProfileVO>({
  userCustomerId: 0,
  isAdmin: 0,
  avatar: "",
  customerRegionId: 0,
  userType: 0,
  hasDevice: 0,
  roleName: "",
});

enum DialogType {
  ACCOUNT = "account",
  PASSWORD = "password",
  MOBILE = "mobile",
  EMAIL = "email",
}

const dialog = reactive({
  visible: false,
  title: "",
  type: "" as DialogType,
});

const userProfileForm = reactive<UserProfileForm>({});
const passwordChangeForm = reactive<PasswordChangeForm>({});
const passwordChangeFormRef = ref<any>();

const mobileCountdown = ref(0);
const mobileTimer = ref<NodeJS.Timeout | null>(null);

const emailCountdown = ref(0);
const emailTimer = ref<NodeJS.Timeout | null>(null);

const formEdit = reactive<any>({
  userFullName: "",
  userPhone: "",
  userEmail: "",
});

const dialogEdit = reactive({
  visible: false,
});

const passwordChangeRules = {
  oldPassword: [
    { required: true, message: t("common.plsInput") + t("profile.oldPasswd"), trigger: "blur" },
  ],
  newPassword: [
    { required: true, message: t("common.plsInput") + t("profile.newPasswd"), trigger: "blur" },
    {
      min: 6,
      message: t("profile.passwdLength"),
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: t("common.plsInput") + t("profile.confirmPasswd"), trigger: "blur" },
  ],
};

const avatarDialog = reactive({
  visible: false,
});
const userAvatar = reactive<any>({
  avatar: "",
});

const handleOpenDialog = (type: DialogType) => {
  dialog.type = type;
  dialog.visible = true;
  switch (type) {
    case DialogType.PASSWORD:
      dialog.title = t("profile.changePasswd");
      break;
  }
};

const handleSubmit = async () => {
  passwordChangeFormRef.value.validate((valid: boolean) => {
    if (valid) {
      if (dialog.type === DialogType.PASSWORD) {
        if (!passwordChangeForm.newPassword || passwordChangeForm.newPassword.length < 6) {
          ElMessage.error(t("profile.passwdLength"));
          return;
        }
        if (passwordChangeForm.newPassword !== passwordChangeForm.confirmPassword) {
          ElMessage.error(t("profile.passwdNotMath"));
          return;
        }
        UserAPI.changePassword(passwordChangeForm).then(() => {
          ElMessage.success(t("profile.passwdSuccess"));
          dialog.visible = false;
        });
      }
    }
  });
};

const loadUserProfile = async () => {
  const data = await UserAPI.getProfile();
  userProfile.value = data;
  userAvatar.avatar = data.avatar;
  formEdit.userFullName = data.userFullName;
  formEdit.userPhone = data.userPhone;
  formEdit.userEmail = data.userEmail;
};

function openUploadDialog() {
  avatarDialog.visible = true;
}

function handleFileChange(file: any) {
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = () => {
    const base64 = reader.result as string;
    userAvatar.avatar = base64;
    UserAPI.uploadAvatar(userAvatar).then((res) => {
      avatarDialog.visible = false;
      upload.value!.clearFiles();
      loadUserProfile();
    });
  };
}

function openEditDialog(key: string) {
  if (key === "userFullName") {
    username.value = true;
  }
  if (key === "userPhone") {
    userphone.value = true;
  }
  if (key === "userEmail") {
    useremal.value = true;
  }
  dialogEdit.visible = true;
}

function handleEditSubmit() {
  let key = "";
  let value = "";
  if (username.value) {
    key = "userFullName";
    value = formEdit.userFullName;
  }
  if (userphone.value) {
    key = "userPhone";
    value = formEdit.userPhone;
  }
  if (useremal.value) {
    key = "userEmail";
    value = formEdit.userEmail;
  }
  UserAPI.updateUserProfile(key, value).then((res) => {
    if (key == "" || value == "") {
      ElMessage.error(t("common.updatedFail"));
    }
    if (res.data.code == 200) {
      ElMessage.success(t("common.updatedSuccess"));
      dialogEdit.visible = false;
      loadUserProfile();
    } else {
      ElMessage.error(res.data.message);
    }
  });
}

function closeEditDialog() {
  dialogEdit.visible = false;
  username.value = false;
  userphone.value = false;
  useremal.value = false;
  loadUserProfile();
}

onMounted(async () => {
  if (mobileTimer.value) {
    clearInterval(mobileTimer.value);
  }
  if (emailTimer.value) {
    clearInterval(emailTimer.value);
  }
  await loadUserProfile();
});
</script>

<style lang="scss" scoped>
.app-container {
  /* 50px = navbar = 50px */
  height: calc(100vh - 50px);
  background: var(--el-fill-color-blank);
}

.hasTagsView {
  .app-container {
    /* 84px = navbar + tags-view = 50px + 34px */
    height: calc(100vh - 84px);
  }
}
</style>
